﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using forum.Data;
using forum.ApplicationCode;
using System.Text;
using System.Threading;

namespace forum.Ajax
{
    /// <summary>
    /// Summary description for forumAjax
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class forumAjax : System.Web.Services.WebService
    {

        [WebMethod]
        public string registration(string Username, string Password)
        {
            using (forumDataContext data = new forumDataContext())
            {
                int isFree = data.sp_IsUserNameFree(Username).FirstOrDefault().Column1.Value;
                if (isFree > 0)
                    return "bad";
                else
                {
                    data.sp_InsertUser(Username, Password);
                    Boolean afterLogin = Membership.Login(Username, Password);
                    if(!afterLogin)
                        return "bad";
                }
                    
            }
            return "ok";

        }

        [WebMethod(EnableSession = true)]
        public string LogOut()
        {
         
            Membership.LogOut();
            Session["unReadThreads"] = null; ;
            Session["unReadPosts"] = null;
            return "ok";
        }


        [WebMethod]
        public string CloseConnection(string srak)
        {
            forumConnection.closeConnection();
            return "ok";

        }


        [WebMethod]
        public string Login(string Username, string Password)
        {
            Boolean afterLogin = Membership.Login(Username, Password);
            if (!afterLogin)
                return "bad";
            return "ok";

        }

        [WebMethod]
        public string addThread(string forumId , string title, string body)
        {

           /* using (forumDataContext data = new forumDataContext())
            {
                data.sp_InsertThread(int.Parse(forumId),Membership.GetUserId(),title,body, DateTime.Now);
            }
           */
             using (forumDataContext data = new forumDataContext())
            {
            //check if not active - and if not change status in subForum to banned
                int isActive = data.sp_IsUserActive(Membership.GetUserId()).FirstOrDefault().Column1.Value;
                if (isActive == 0)
                {
                    int inBannedTable = data.sp_IsUSerInBannedTable(Membership.GetUserId(), int.Parse(forumId)).FirstOrDefault().Column1.Value;

                    if (inBannedTable == 0)
                        data.sp_IsertUserToBannedTable(Membership.GetUserId(), int.Parse(forumId));
                }

            }
            forumConnection.addThread(forumId, title, body);
            
            return "ok";

        }

        [WebMethod]
        public string deleteThread(string threadId)
        {

            using (forumDataContext data = new forumDataContext())
            {
                data.sp_deleteThreadPosts(int.Parse(threadId));
                data.sp_deleteThread(int.Parse(threadId));
            }

            return "ok";

        }


        [WebMethod]
        public string getThreadDetails(string threadId)
        {
            string title, content;
            using (forumDataContext data = new forumDataContext())
            {
                var thread = data.sp_GetThreadDetails(int.Parse(threadId)).FirstOrDefault();
                title = thread.threadTitle;
                content = thread.threadContent;
            }
            string ans = title + "," + content;
            return ans;

        }

        [WebMethod]
        public string editThread(string threadId, string title, string body)
        {
          /*  using (forumDataContext data = new forumDataContext())
            {
                data.sp_updateThread(int.Parse(threadId), title, body);

            }
          */

            forumConnection.editThread(threadId, title, body);
           
            return "ok";

        }



        [WebMethod]
        public string addPost(string threadId, string title, string body)
        {

            /*using (forumDataContext data = new forumDataContext())
            {
                //0 means it post to thred and not post to post
                data.sp_InsertPost(int.Parse(threadId), Membership.GetUserId(),0, title, body, DateTime.Now);
            }*/

            using (forumDataContext data = new forumDataContext())
            {
                //check if not active - and if not change status in subForum to banned
                int isActive = data.sp_IsUserActive(Membership.GetUserId()).FirstOrDefault().Column1.Value;
                if (isActive == 0)
                {
                    var threadDetalis = data.sp_getThreadFullDetails(int.Parse(threadId)).FirstOrDefault();
                    int inBannedTable = data.sp_IsUSerInBannedTable(Membership.GetUserId(), threadDetalis.subForumId).FirstOrDefault().Column1.Value;

                    if (inBannedTable == 0)
                        data.sp_IsertUserToBannedTable(Membership.GetUserId(), threadDetalis.subForumId);
                }

            }

            forumConnection.addPost(threadId, title, body);

            return "ok";

        }


        [WebMethod]
        public string deletePost(string postId)
        {

            using (forumDataContext data = new forumDataContext())
            {
                data.sp_deletePostsToPosts(int.Parse(postId));
                data.sp_deletePost(int.Parse(postId));
            }

            return "ok";

        }


        [WebMethod]
        public string getPostDetails(string postId)
        {
            string title, content;
            using (forumDataContext data = new forumDataContext())
            {
                var post = data.sp_GetPostDetails(int.Parse(postId)).FirstOrDefault();
                title = post.postTitle;
                content = post.postContent;
            }
            string ans = title + "," + content;
            return ans;

        }

        [WebMethod]
        public string editPost(string postId, string title, string body)
        {
            /*using (forumDataContext data = new forumDataContext())
            {
                data.sp_updatePost(int.Parse(postId), title, body);

            }
             * */

            forumConnection.editPost(postId, title, body);
            return "ok";

        }


        [WebMethod]
        public string deleteSubForum(string forumId)
        {
            using (forumDataContext data = new forumDataContext())
            {

                //remove from banned users

                data.sp_DeleteSubForumFromBannedUsers(int.Parse(forumId));

                //remove all forum posts
                var allPosts = data.sp_GetAllPosts();
                foreach (var post in allPosts)
                {
                    var isBelongToForum = data.sp_isPostBelongsToForum(post.postId, int.Parse(forumId)).FirstOrDefault().isBelong.Value;
                    if (isBelongToForum ==1)
                        data.sp_deletePost(post.postId);

                }

                //remove all forum posts
                data.sp_deleteForumThreads(int.Parse(forumId));
                data.sp_deleteForumModerators(int.Parse(forumId));
                data.sp_deleteSubForum(int.Parse(forumId));
            }
            return "ok";
        }





        [WebMethod(EnableSession = true)]
        public string updateAddForumSession(string forumName)
        {
            Session["addSubForumName"] = forumName;

            return "ok";
        }


        [WebMethod]
        public string getModeratorsBySubForum(string subForumName)
        {
            List<ForumItem> lst = ListManager.GetModeratorsBySubForum(subForumName);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<option value=\"{0}\">{1}</option>", "0", "Choose Mooderator ");
            foreach (var user in lst)
            {
                sb.AppendFormat("<option value=\"{0}\">{1}</option>", user._Value, user._Text);
            }

            return  sb.ToString();


        }

        [WebMethod]
        public string getSubForumModerateCandidates(string subForumName)
        {
            List<ForumItem> lst = ListManager.GetSubForumCandidateModerators(subForumName);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<option value=\"{0}\">{1}</option>", "0", "Choose Mooderator ");
            foreach (var user in lst)
            {
                sb.AppendFormat("<option value=\"{0}\">{1}</option>", user._Value, user._Text);
            }

            return sb.ToString();


        }

   
        [WebMethod]
        public string removeModerator(string subForumId, string moderatorName)
        {
           /* using (forumDataContext data = new forumDataContext())
            {

                data.sp_RemoveModerator(int.Parse(subForumId), int.Parse(moderatorId));
            }
            */
            forumConnection.removeModerator(int.Parse(subForumId), moderatorName);

            return "ok";
        }

        
        [WebMethod]
        public string complaineModerator(string subForumId, string moderatorId)
        {
            int mId = int.Parse(moderatorId);
            int fId = int.Parse(subForumId);
            int complaintNum = 0;
            using (forumDataContext data = new forumDataContext())
            {
                complaintNum = data.sp_GetModeratorDetails(fId, mId).FirstOrDefault().complaintNumber;
                int tmp = complaintNum + 1;
                data.sp_UpdateComplaine(int.Parse(subForumId), int.Parse(moderatorId), tmp);
            }
            return "ok";
        }

        [WebMethod]
        public string AddModerator(string subForumId, string userId)
        {
            using (forumDataContext data = new forumDataContext())
            {

                data.sp_AddModerator(int.Parse(subForumId), int.Parse(userId), DateTime.Now);
            }
            return "ok";
        }

        [WebMethod]
        public string getUserNumberOfMessages(string userName)
        {
            int totalMessages=0;
            using (forumDataContext data = new forumDataContext())
            {
                int userId = data.sp_GetUserIdByUserName(userName).FirstOrDefault().userId;
                var subForums = data.sp_GetSubForumList();
                foreach (var forum in subForums)
                {
                    int posts = data.sp_GetUserNumberOfPostInSubForum(forum.subForumId, userId).FirstOrDefault().numOfPosts.Value;
                    int threads = data.sp_GetUserNumberOfThreadsInSubForum(forum.subForumId, userId).FirstOrDefault().numOfThreads.Value;
                    totalMessages = totalMessages + posts + threads;
                }
            }
            return totalMessages.ToString();
        }


        [WebMethod]
        public string getTotalMessages(string srak)
        {

            int totalMessages = 0;
            using (forumDataContext data = new forumDataContext())
            {
                int threadsNum = data.sp_GetNumberOfThreads().FirstOrDefault().numOfThreads.Value;
                int postsNum = data.sp_GetNumberOfPosts().FirstOrDefault().numOfPosts.Value;
                totalMessages = threadsNum + postsNum;
            }
            return totalMessages.ToString();
        }


        [WebMethod]
        public string addPostToPost(string postId, string title, string body)
        {

            using (forumDataContext data = new forumDataContext())
            {
                int threadId = data.sp_getPostFullDetails(int.Parse(postId)).FirstOrDefault().threadId;
                data.sp_InsertPost(threadId, Membership.GetUserId(), int.Parse(postId), title, body, DateTime.Now);
            }

            return "ok";

        }

           [WebMethod]
        public string changeAdmin(string userId)
        {

            using (forumDataContext data = new forumDataContext())
            {
                data.sp_RemoveAdmin(Membership.GetUserId());
                data.sp_ChangeAdmin(int.Parse(userId));
            }

            return "ok";

        }

           [WebMethod]
           public string getNewTitles(string SubForumId)
           {
               string ans = "";
               using (forumDataContext data = new forumDataContext())
               {
                   var threads = data.sp_GetSubForumThreads(int.Parse(SubForumId));
                   foreach (var Thread in threads)
                   {
                       ans =ans+ Thread.threadTitle + "," + Thread.threadId + "#";

                   }


                   return ans;

               }
           }
            

            /*
            
           [WebMethod(EnableSession = true)]
           public string checkForThreadsUpdates(string srak)
           {
               //check if user member in sub forum (wrote a message/post there
               if (Session["mySubForumList"] != null)
               {

                   Boolean updated = false;
                   string ans = "";
                   Dictionary<int, int> tmp = Session["mySubForumList"] as Dictionary<int, int>;
                   using (forumDataContext data = new forumDataContext())
                   {
                       foreach (var a in tmp)
                       {
                           int subForumId = a.Key;
                           int lastThread = a.Value;
                           //check if still have a msg in this sub forum
                           int haveThread = data.sp_GetSubForumsWithMyThreads(Membership.GetUserId(), subForumId).FirstOrDefault().numOfThreads.Value;
                           if (haveThread > 0)
                           {
                               int newLastThread = data.sp_GetLastThreadInSubForum(subForumId).FirstOrDefault().threadId;
                               if (lastThread < newLastThread)
                               {
                                   string newThreadTitle= data.sp_GetThreadDetails(newLastThread).FirstOrDefault().threadTitle;
                                   ans = ans + subForumId.ToString() + "," + newLastThread.ToString() + "," + newThreadTitle;
                                   tmp[subForumId] = newLastThread;
                                   if (Session["unreadThreads"] == null)
                                   {
                                       List<int> unreadThreads = new List<int>();
                                       unreadThreads.Add(newLastThread);
                                       Session["unreadThreads"] = unreadThreads;
                                   }
                                   else
                                   {
                                       List<int> unreadThreads = Session["unreadThreads"] as List<int>;
                                       unreadThreads.Add(newLastThread);
                                       Session["unreadThreads"] = unreadThreads;
                                   }
                                   return ans;
                               }
                           }
                           //remove subforum from my threads list
                           else
                           {
                               tmp.Remove(subForumId);
                           }
                       }
                   }
                   Session["mySubForumList"] = tmp;
                   //return list of subforums and last thread id in this sub forum
                   if (updated)
                       return ans;
                   else
                       return "bad";
               }

               else
               {
                   return "bad";
               }
           }

            */

           [WebMethod(EnableSession = true)]
           public string getUnreadFeeds(string srak)
           {
               string ans = "";
               if (Session["unreadThreads"] != null)
               {

                   
                   List<int> unreadThreads  = Session["unreadThreads"] as List<int>;
                   using (forumDataContext data = new forumDataContext())
                   {
                       foreach (int thread in unreadThreads)
                       {
                           int threadId = thread;
                           int isThreadExists = data.sp_IsThreadExists(threadId).FirstOrDefault().Column1.Value;
                           if(isThreadExists>0)
                           {
                               var threadDetail = data.sp_GetThreadDetails(threadId).FirstOrDefault();
                               string threadTitle = threadDetail.threadTitle;
                               string threadContent = threadDetail.threadContent;

                               ans = ans + "threadPopUp" + "," + threadId.ToString() + "," + threadTitle + "," + threadContent + "#";
                           }

                       }
                    }
               }

               if (Session["unreadPosts"] != null)
               {
                   List<int> unreadPosts  = Session["unreadPosts"] as List<int>;
                   using (forumDataContext data = new forumDataContext())
                   {
                       foreach (int post in unreadPosts)
                       {
                           int postId = post;
                           int isPostExists = data.sp_IsPostExists(postId).FirstOrDefault().Column1.Value;
                           if(isPostExists>0)
                           {
                               var postDetail = data.sp_getPostFullDetails(postId).FirstOrDefault();
                               string postTitle = postDetail.postTitle;
                               string postContent = postDetail.postContent;

                               ans = ans +"postPopUp" +"," + postId.ToString() + "," + postTitle + "," + postContent +"#";
                           }

                       }
                    }
               }

              if (ans !="")
               return ans;
              else
                  return "bad";
           }

           [WebMethod]
           public string activeUser(string srak)
           {
               using (forumDataContext data = new forumDataContext())
               {
                   int isActive = data.sp_IsUserActive(Membership.GetUserId()).FirstOrDefault().Column1.Value;
                   if (isActive > 0)
                       forumConnection.DeActiveUser();
                     //  data.sp_DeActiveUser(Membership.GetUserId());
                   else
                      // data.sp_ActiveUser(Membership.GetUserId());
                         forumConnection.ActiveUser();
               }
               return "ok";
           }

           [WebMethod]
           public string getBannedUsersBySubForum(string subForumId)
           {
               List<ForumItem> lst = ListManager.GetCandidateBannedUsers(int.Parse(subForumId));

               StringBuilder sb = new StringBuilder();
               sb.AppendFormat("<option value=\"{0}\">{1}</option>", "0", "Choose User ");
               foreach (var user in lst)
               {
                   sb.AppendFormat("<option value=\"{0}\">{1}</option>", user._Value, user._Text);
               }

               return sb.ToString();


           }

           [WebMethod]
           public string getUnBannedUsersBySubForum(string subForumId)
           {
               List<ForumItem> lst = ListManager.GetBannedUsers(int.Parse(subForumId));

               StringBuilder sb = new StringBuilder();
               sb.AppendFormat("<option value=\"{0}\">{1}</option>", "0", "Choose User ");
               foreach (var user in lst)
               {
                   sb.AppendFormat("<option value=\"{0}\">{1}</option>", user._Value, user._Text);
               }

               return sb.ToString();


           }

          [WebMethod]
           public string banUser(string forumId,string userId)
           {


               using (forumDataContext data = new forumDataContext())
               {
                   data.sp_BanUSer(int.Parse(forumId), int.Parse(userId));
               }

               return "ok";

           }

          [WebMethod]
          public string UnbanUser(string forumId, string userId)
          {


              using (forumDataContext data = new forumDataContext())
              {
                  data.sp_UnBanUSer(int.Parse(forumId), int.Parse(userId));
              }

              return "ok";

          }

          [WebMethod(EnableSession = true)]
          public string checkForUpdates(string location , string query)
          {
              List<int> unReadThreads = Session["unReadThreads"] as List<int>;
              List<int> unReadPosts = Session["unReadPosts"] as List<int>;
              if (unReadThreads == null)
                  unReadThreads = new List<int>();
              if (unReadPosts == null)
                  unReadPosts = new List<int>();
              List<int> refreshedThreads = new List<int>();
              List<int> refreshedPosts = new List<int>();
              int queryString = 0; ;
              if (query!="")
                queryString = int.Parse(query);

              string ans = "";
              string newThreads;
              string newPosts;
              string newRefreshThreads;
              string newRefreshPosts;
              while ((newThreads = webInteractiveMessage.getNewThreadMessage()) != "")
              {
                  using (forumDataContext data = new forumDataContext())
                  {
                      int threadId = int.Parse(newThreads);
                      var threadDetails = data.sp_getThreadFullDetails(threadId).FirstOrDefault();
                      if (threadDetails.ownerId != Membership.GetUserId())
                      {
                          string threadOwner = threadDetails.userName;
                          string threadTitle = threadDetails.threadTitle;
                          string threadContent = threadDetails.threadContent;
                          string threadCreation = threadDetails.creationDate.ToString();
                          string needToRefresh = "false";
                          if (location == "SubForum" && queryString == threadDetails.subForumId && !refreshedThreads.Contains(threadId))
                          {
                              needToRefresh = "true";
                              refreshedThreads.Add(threadId);
                          }
                          else
                          {
                              unReadThreads.Add(threadId);

                          }
                          ans = ans + "threadPopUp" + "," + threadId.ToString() + "," + threadOwner + "," + threadTitle + "," +
                                threadContent + "," + threadCreation + "," + needToRefresh + "#";
                      }
                  }

              }

              while ((newPosts = webInteractiveMessage.getNewPostMessage()) != "")
              {
                  using (forumDataContext data = new forumDataContext())
                  {
                      int postId = int.Parse(newPosts);
                      var postDetails = data.sp_getPostFullDetails(postId).FirstOrDefault();
                      if (postDetails.ownerId != Membership.GetUserId())
                      {
                          string postOwner = data.sp_GetUserNameByUserId(postDetails.ownerId).FirstOrDefault().userName;
                          string postTitle = postDetails.postTitle;
                          string postContent = postDetails.postContent;
                          string postCreation = postDetails.creationDate.ToString();
                          string needToRefresh = "false";
                          if (location == "Thread" && queryString == postDetails.threadId && !refreshedPosts.Contains(postId))
                          {
                              needToRefresh = "true";
                              refreshedPosts.Add(postId);
                          }
                          else
                          {
                              unReadPosts.Add(postId);

                          }

                          ans = ans + "postPopUp" + "," + postId.ToString() + "," + postOwner + "," + postTitle + "," +
                                postContent + "," + postCreation + "," + needToRefresh + "#";
                      }
                  }
              }
              
              while ((newRefreshThreads = webInteractiveMessage.getNewRefreshThreadMessage()) != "")
              {
                  using (forumDataContext data = new forumDataContext())
                  {
                      int threadId = int.Parse(newRefreshThreads);
                      var threadDetails = data.sp_getThreadFullDetails(threadId).FirstOrDefault();
                      if (threadDetails.ownerId != Membership.GetUserId())
                      {
                          string threadOwner = threadDetails.userName;
                          string threadTitle = threadDetails.threadTitle;
                          string threadContent = threadDetails.threadContent;
                          string threadCreation = threadDetails.creationDate.ToString();
                          //check if need to refresh
                          if (location == "SubForum" && queryString == threadDetails.subForumId  && !refreshedThreads.Contains(threadId))
                          {
                             refreshedThreads.Add(threadId);
                              ans = ans + "threadRefresh" + "," + threadId.ToString() + "," + threadOwner + "," + threadTitle + "," +
                                    threadContent + "," + threadCreation + "," + "true"+ "#";
                          }
                      }
                  }

              }
              
              while ((newRefreshPosts = webInteractiveMessage.getNewRefreshPostMessage()) != "")
              {
                  using (forumDataContext data = new forumDataContext())
                  {
                      int postId = int.Parse(newRefreshPosts);
                      var postDetails = data.sp_getPostFullDetails(postId).FirstOrDefault();
                      if (postDetails.ownerId != Membership.GetUserId())
                      {
                          string postOwner = data.sp_GetUserNameByUserId(postDetails.ownerId).FirstOrDefault().userName;
                          string postTitle = postDetails.postTitle;
                          string postContent = postDetails.postContent;
                          string postCreation = postDetails.creationDate.ToString();
                          //check if need to refresh
                          if (location == "Thread" && queryString == postDetails.threadId && !refreshedPosts.Contains(postId))
                          {
                              refreshedPosts.Add(postId);
                              ans = ans + "postRefresh" + "," + postId.ToString() + "," + postOwner + "," + postTitle + "," +
                                    postContent + "," + postCreation + "," + "true"+ "#";
                          }
                      }
                  }

              }

              Session["unReadThreads"] = unReadThreads;
              Session["unReadPosts"]  = unReadPosts;
              
              if ( ans!="")
                return ans;

               return "bad";

          }

        

    }
}
